package com.itheima.response;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取需要下载资源的文件名
        String filename = req.getParameter("filename");
        ServletContext sc = getServletContext();
        String MineType= sc.getMimeType(filename);
        //1设置content-type响应头，值是要下载的文件的mime类型
       resp.setHeader("content-type",MineType);
        //2.设置content-disposition响应头，值是attachment；filename=文件名
      resp.setHeader("content-disposition","attachment;filename="+URLEncoder.encode(filename,"utf-8"));

        //3.通过字节输入流读取需要下载的那个文件，利用网络输出流写道浏览器即可
        InputStream is = sc.getResourceAsStream("/" + filename);
        ServletOutputStream os = resp.getOutputStream();
        byte [] bytes = new byte[1024];
        int len ;
        while ((len=is.read(bytes))!=-1){
            os.write(bytes,0,len);
        }
        is.close();

    }
}
